package mavenWebProject;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * Servlet implementation class CarServlet
 */
@WebServlet("/CarServlet")
public class CarServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CarServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		
		int id=Integer.valueOf(request.getParameter("carId"));
		String name=request.getParameter("name");
		String size=request.getParameter("size");
		String temp=request.getParameter("doWhat");
		HttpSession session=request.getSession();
		String username=(String) session.getAttribute("username");
		//1.加载mybatis的核心配置文件，获取sqlsessionfactory
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		//2.获取sqlsession对象，用它来执行sql
		SqlSession sqlsession=sqlSessionFactory.openSession();
		//3.获取mapper接口的代理对象
		productsMapper mapper=sqlsession.getMapper(productsMapper.class);
		mapper.deleteFromCar(username,id);
		sqlsession.commit();
		if(temp!=null) {
			request.getRequestDispatcher("personalDetails.jsp").forward(request, response);
		}else {
			request.getRequestDispatcher("messagePage.jsp?message=商品删除成功").forward(request, response);
			sqlsession.close();
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
